<template>
  <div class="register-main">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户注册</span>
        </div>
      </template>
      <div class="card-body">
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="70px" class="demo-ruleForm">
          <el-form-item label="邮箱" prop="username">
            <el-input v-model="ruleForm.username" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="ruleForm.nickname" autocomplete="off" />
          </el-form-item>
          <!-- <el-form-item label="验证码" prop="captcha">
            <div class="input-container">
              <el-input v-model="ruleForm.captcha" class="input-field" />&nbsp
              <el-button type="primary" @click="onShow('blockPuzzle')" :disabled="countdown > 0">
                {{ countdown > 0 ? countdown + ' 秒后重新获取' : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)" :style="{ width: '100%' }" color="#035D1C">注册</el-button>
          </el-form-item>
        </el-form>
        <p style="text-align: center;">已有账号? <router-link to="/login">点击登录</router-link>.</p>
      </div>
    </el-card>
    <!-- <Verify mode="pop" :captchaType="captchaType" :imgSize="{ width: '400px', height: '200px' }" ref="verify"
    @success="handleSuccess" ></Verify> -->
  </div>
</template>

<script lang="ts" setup>
import { FormInstance, FormRules } from 'element-plus';
// import Verify from '../components/verifition/Verify.vue'
// import { SendCaptchaEmailApi } from '../api/captcha.ts'
import { RegisterAPI } from '../api/user.ts'
import { useRouter } from 'vue-router'

const ruleFormRef = ref<FormInstance>()

const checkEmail = (_rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入邮箱'))
  }
  const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(value)) {
    return callback(new Error('请输入有效的邮箱'))
  }
  callback()
}

const checkNickname = (_rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入昵称'))
  }
  callback()
}

const validatePass = (_rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入密码'))
  } 
  callback()
}

const ruleForm = reactive({
  password: '',
  nickname: '',
  username: ''
})

const rules = reactive<FormRules<typeof ruleForm>>({
  password: [{ validator: validatePass, trigger: 'blur' }],
  nickname: [{ validator: checkNickname, trigger: 'blur' }],
  username: [{ validator: checkEmail, trigger: 'blur' }]
})

const router = useRouter()

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      RegisterAPI(ruleForm)
      .then((res) => {
        if(res.code === 200&&res.msg!==null){
          ElMessage.success(res.msg)
          router.push("/login")
        }
        if(res.code === 100&&res.msg!==null){
          ElMessage.error(res.msg)
        }

    })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

// const resetForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return
//   formEl.resetFields()
// }


// const verify = ref<null | { show: () => void }>(null);
// const captchaType = ref('');
// const onShow = (type: string) => {
//   if (!ruleForm.email) {
//     ElMessage.error("请输入邮箱")
//     return
//   }
//   const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
//   if (!emailRegex.test(ruleForm.email)) {
//     ElMessage.error("请输入有效邮箱")
//     return
//   }
//   captchaType.value = type;
//   if (verify.value !== null) {
//     verify.value.show();
//   }
// }

// const handleSuccess = () => {
//   SendCaptchaEmailApi({email: ruleForm.email})
//   .then((res) => {
//          console.log(res)
//     })
//   startCountdown()
// }

// const countdown = ref(0);
// let timer: number | null = null;

// // 开始倒计时
// const startCountdown = () => {
//   if (countdown.value === 0) {
//     countdown.value = 60;
//     runCountdown();
//   }
// };

// const runCountdown = () => {
//   timer = window.setInterval(() => {
//     countdown.value--;
//     if (countdown.value === 0) {
//       window.clearInterval(timer!);
//     }
//   }, 1000);
// };

// // 监听倒计时的变化，保存到localStorage
// watch(countdown, val => {
//   localStorage.setItem('countdown', JSON.stringify(val));
// });

// // 加载组件时恢复倒计时状态
// onMounted(() => {
//   const savedCountdown = JSON.parse(localStorage.getItem('countdown') as string);
//   if (savedCountdown && savedCountdown > 0) {
//     countdown.value = savedCountdown;
//     runCountdown();
//   }
// });

// // 在组件卸载前清除定时器
// onBeforeUnmount(() => {
//   if (timer) {
//     clearInterval(timer);
//   }
// });

</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: large;
  font-weight: bold;
}

.card-body {
  width: 93%;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card {
  width: 350px;
  height: 330px;
}

.register-main {
  background-image: url("../assets/img/rice.png");
  background-size: cover;
  background-position: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.input-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
